import 'dart:io';
import 'package:jm_flutter_common/jm_flutter_common.dart';
import 'package:share_plus/share_plus.dart';
import '../model/app_file_desc.dart';

class AppFileUtil {
  static const _tag = "AppFileUtil";
  static Future<List<AppFileDesc>> getFiles({required String dirPath}) async {
    final files = <AppFileDesc>[];
    final dir = Directory(dirPath);
    if (!dir.existsSync()) {
      logd(_tag, "$dirPath, 目录不存在");
      return files;
    }

    final fileList = dir.list();

    await for (FileSystemEntity fileSystemEntity in fileList) {
      files.add(AppFileDesc.formFileSystemEntity(fileSystemEntity));
    }

    return files;
  }

  static Future<void> deleteFile(String filePath) async {
    logd(_tag, "删除文件 $filePath");
    final file = File(filePath);
    if (!file.existsSync()) {
      logd(_tag, "$filePath, 文件不存在");
      return;
    }
    await file.delete();
  }

  static Future<bool> shareFiles(List<AppFileDesc> files) async {
    final xFiles = files.map((e) => XFile(e.path)).toList();

    final ret = await Share.shareXFiles(xFiles);
    if (ret.status == ShareResultStatus.success) {
      return true;
    }

    return false;
  }

  static Future<void> deleteFiles(List<AppFileDesc> files) async {
    for (final file in files) {
      await deleteFile(file.path);
    }
  }
}
